import subprocess
import asyncio

from fastapi import FastAPI

from logger import logger
import docker
from server.api.routes import router

app = FastAPI()
logger = logger.ServiceLogger()



def is_container_running(container_name: str) -> bool:
    client = docker.from_env()
    try:
        container = client.containers.get(container_name)
        return container.status == "running"
    except docker.errors.NotFound:
        return False


def start_or_stop_container(action, container_name):
    """启动或停止Triton容器的抽象函数"""
    try:
        if not is_container_running(container_name):
            subprocess.call(["./docker/start-stop.bat", action])
            logger.log_container_action(action, "success")
    except Exception as e:
        logger.error(f"Error executing container {action}: {e}")

async def main():
    try:
        # 注册路由
        app.include_router(router)

        # 启动Triton容器，异步调用并捕获异常
        await asyncio.gather(
            start_or_stop_container_async("start", "triton_server"),
            return_exceptions=True
        )

        # ...（主程序运行逻辑）

    except Exception as e:
        logger.error(f"主程序运行时发生异常: {e}")
    finally:
        # 确保停止Triton容器，异步调用
        await start_or_stop_container_async("stop", "triton_server")

async def start_or_stop_container_async(container_command, container_name):
    """
    异步启动或停止指定的容器。
    """
    try:
        if container_command == "start":
            logger.message(f"正在启动 {container_name} 容器的逻辑")
            # await start_container(container容器...")
            await start_or_stop_container(container_command,container_name)
            # 实现启动_name)
        elif container_command == "stop":
            logger.message(f"正在停止 {container_name} 容器...")
            # 实现停止容器的逻辑
            # await stop_container(container_name)
            await start_or_stop_container(container_command,container_name)
        else:
            raise ValueError(f"无效的容器操作命令: {container_command}")
    except Exception as e:
        logger.error(f"处理 {container_command} 容器时发生错误: {e}")

if __name__ == "__main__":
    asyncio.run(main())
